package Link;

import java.util.List;
import java.util.Stack;

public class BM11 {
    public class ListNode {
        int val;
        BM13.ListNode next = null;
        public ListNode(int val) {
            this.val = val;
        }
    }

    //链表相加(二)
    //    public ListNode ReverseList(ListNode pHead) {
//        if (pHead == null) {
//            return null;
//        }
//
//        Stack<ListNode> stack = new Stack<>();
//        ListNode temp = pHead;
//
//        while (temp != null) {
//            stack.push(temp);
//            temp = temp.next;
//        }
//
//        ListNode newHead = null;
//
//        while (!stack.isEmpty()) {
//            temp = stack.pop();
//            temp.next = newHead;
//            newHead = temp;
//        }
//        temp.next = null;
//
//        return newHead;
//    }

    public ListNode ReverseList(ListNode pHead) {
        if (pHead == null) {
            return null;
        }

        ListNode prev = null;
        ListNode cur = pHead;

        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }

        return prev;
    }

    public ListNode addInList (ListNode head1, ListNode head2) {
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }

        head1 = ReverseList(head1);
        head2 = ReverseList(head2);

        ListNode res = new ListNode(-1);
        ListNode head = res;

        int carry = 0;

        while (head1 != null || head2 != null || carry != 0) {
            int val1 = (head1 == null ? 0:head1.val);
            int val2 = (head2 == null ? 0:head2.val);

            int temp = val1 + val2 + carry;

            carry = temp / 10;
            temp %= 10;

            head.next = new ListNode(temp);
            head = head.next;

            if (head1 != null) {
                head1 = head1.next;
            }
            if (head2 != null) {
                head2 = head2.next;
            }
        }
        return ReverseList(res.next);
    }

}
